import datetime
from pao.models import Department, Project
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

def parseDateFromString(date, sep = "-"):
    if date == None:
        return None

    try:
        year, month = date.split(sep)
        year, month = int(year),int(month)
        return datetime.date(year, month, 1) #default day 1, not important for us
    except ValueError:
        return None

def getUserGroups(user):
    if user.is_staff:
        return ['Admin']
    else:
        return [x.name for x in user.groups.all()]

def hasPermissions(user, level, id=None):
    groups = getUserGroups(user)
    if level == 'Enterprise':
        higher = 'Enterprise' in groups
        return higher
    elif level == 'Department':
        higher = 'Enterprise' in groups
        current = 'DepartmentManager' in groups
        try:
            department = Department.objects.filter(id__exact=id)[0]
            owner = (department.manager.id == user)
        except:
            owner = False
        return higher or (current and owner)
    elif level == 'Project':
        higher = ('Enterprise' in groups) or ('DepartmentManager' in groups)
        current = 'ProjectManager' in groups
        try:
            project = Project.objects.filter(id__exact=id)[0]
            owner = (project.manager.id == user)
        except ObjectDoesNotExist:
            Owner = False
        except AttributeError:
            Owner = False
        return higher or (current and owner)
    elif level == 'Personal':
        higher = ('Enterprise' in groups) or ('DepartmentManager' in groups) or ('ProjectManager' in groups)
        current = 'Employee' in groups
        try:
            u = User.objects.filter(username__exact=id)[0]
            owner = (u == user)
        except ObjectDoesNotExist:
            Owner = False
        return higher or (current and owner)
    else:
        return False

def rememberDates(request, start, end):
    if request.session.has_key('startDate') and request.session.has_key('endDate'):
        request.session['startDate'] = start
        request.session['endDate'] = end

def generateYears():
    return range(1990, datetime.datetime.now().year+1)
    
